<template>
  <div class="search">
    <!-- 头部 -->
    <van-nav-bar title="搜索中心"
                 left-arrow
                 @click-left="$router.back()"></van-nav-bar>
    <!-- 搜索 -->
    <van-search v-model.trim="keyword"
                show-action
                shape="round"
                placeholder="请输入搜索关键词"
                @input="inputFn"
                @search="search(keyword)">
      <template #action>
        <div @click="search(keyword)">搜索</div>
      </template>
    </van-search>
    <!-- 推荐 -->
    <van-cell-group v-if="sugList.length >0">
      <van-cell icon="search"
                v-for="(item, index) in sugList"
                :key="index"
                @click="search(item)">
        <template #title>
          <div v-html="higLight(item)">搜索</div>
        </template>
      </van-cell>

    </van-cell-group>
    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell :title="item"
                v-for="item in searchList"
                :key="item"
                @click="search(item)">
        <van-icon name="close"
                  @click="del(item)" />
      </van-cell>

    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search'
import { setHistory, getHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      keyword: '',
      // 推荐列表
      sugList: [],
      // 搜索关键词
      searchList: getHistory()
    }
  },
  methods: {
    inputFn() {
      // 防抖 用定时器处理输完等0.5秒显示推荐
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.keyword) {
          // 清空一下推荐数组中的数据 不然历史记录显示不出来
          this.sugList = []
          return
        }
        const res = await getSuggestion(this.keyword)
        // console.log(res)
        this.sugList = res.data.options
      }, 500)
    },
    // 高亮
    higLight(str) {
      const reg = new RegExp(this.keyword, 'gi')
      return str.replace(reg, match => {
        return `<span style="color: red;">${match}</span>`
      })
    },
    // 添加-跳转
    search(keyword) {
      // 判断不能为空
      if (!keyword) return this.$toast('请输入关键词')
      // 添加历史记录
      this.searchList = this.searchList.filter(item => item !== keyword)
      this.searchList.unshift(keyword)
      // 存储数据
      setHistory(this.searchList)
      // 跳转到搜索结果页面
      this.$router.push({
        path: '/search/result',
        query: {
          keyword
        }
      })
    },
    // 删除
    del(keyword) {
      this.searchList = this.searchList.filter(item => item !== keyword)
      // 存储数据
      setHistory(this.searchList)
    }
  }

}
</script>

<style>
</style>
